﻿using HuiJiYunGo.EF;
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace HuiJiYunGO.Controllers
{
    public class SearchController : BaseController
    {
        /// <summary>
        /// 好物精选-商品搜索
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        // GET: Search
        public ActionResult Index(string Key = "", int Page = 1, int? ep = null, int? sp = null, string cat = "",string sort= "")
        {
            var MaterialId = GetAppBarList().Where(m => m.Code == "Search").FirstOrDefault().Material_ID;
            ViewBag.AppBarCode = "Search";

            if (string.IsNullOrWhiteSpace(Key))
            {
                Key = "综合";
            }

            ViewBag.Key = Key;
            ViewBag.Page = Page;
            
            if (string.IsNullOrWhiteSpace(sort)) {
                sort = "tk_total_sales_des";
            }
            ViewBag.Sort = sort;
            ViewBag.Cat = cat;
            ITopClient client = new DefaultTopClient(url, appkey, secret);
            TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
            req.StartDsr = null;
            req.PageSize = 15;
            req.PageNo = Page;
            req.Platform = 1L;
            req.EndTkRate = null;
            req.StartTkRate = null;
            req.EndPrice = ep;
            req.StartPrice = sp;
            req.IsOverseas = false;
            req.IsTmall = true;
            req.Sort = sort;
            req.Itemloc = null;
            req.Cat = cat;
            req.Q = Key;
            req.MaterialId = MaterialId;
            req.HasCoupon = true;
            req.Ip = null;
            req.AdzoneId = adzoneId;
            req.NeedFreeShipment = true;
            req.NeedPrepay = true;
            req.IncludePayRate30 = true;
            req.IncludeGoodRate = true;
            req.IncludeRfdRate = true;
            req.NpxLevel = 2L;
            req.EndKaTkRate = null;
            req.StartKaTkRate = null;
            req.DeviceEncrypt = null;
            req.DeviceValue = null;
            req.DeviceType = null;
            req.LockRateEndTime = null;
            req.LockRateStartTime = null;
            req.Longitude = null;
            req.Latitude = null;
            req.CityCode = null;
            req.SellerIds = null;
            req.SpecialId = null;
            req.RelationId = null;
            TbkDgMaterialOptionalResponse rsp = client.Execute(req);
            if (rsp.IsError) {
                //失败就在来一次
                rsp = client.Execute(req);
            }
            //Console.WriteLine(rsp.Body);
            ViewBag.TotalResults = rsp.TotalResults;
            ViewBag.ResultList = rsp.ResultList;

            List<CategoryLevelOneViewModel> clvm = new List<CategoryLevelOneViewModel>();
            foreach (var item in rsp.ResultList)
            {
                if (!clvm.Any(m => m.id == item.LevelOneCategoryId))
                {
                    clvm.Add(new CategoryLevelOneViewModel()
                    {
                        id = item.LevelOneCategoryId,
                        name = item.LevelOneCategoryName,
                        al_id = item.LevelOneCategoryId.ToString(),
                        CategoryList = new List<CategoryViewModel>() { new CategoryViewModel() {
                         id=item.CategoryId,name=item.CategoryName, al_id = item.CategoryId.ToString()
                        } }
                    }); ;

                }
                else
                {

                    if (!clvm.Find(m => m.id == item.LevelOneCategoryId).CategoryList.Any(m => m.id == item.CategoryId))
                    {

                        clvm.Find(m => m.id == item.LevelOneCategoryId).CategoryList.Add(new CategoryViewModel()
                        {
                            id = item.CategoryId,
                            name = item.CategoryName,
                            al_id = item.CategoryId.ToString()
                        });
                    }
                }

            }

            ViewBag.CategoryList = clvm;

            //同步到数据库

            HuiJiDBContainer db = new HuiJiDBContainer();
            foreach (var item in clvm)
            {
                if (!db.Category.Any(m => m.Ali_id == item.id.ToString() && m.Pid == 0))
                {
                    //一级类目
                    db.Category.Add(new Category()
                    {
                        Name = item.name,
                        ShortName = item.name,
                        Ali_id = item.id.ToString(),
                        ShowWeb = false,
                        ShowPhone = false,
                        UpdateTime = DateTime.Now,
                        CreateTime = DateTime.Now,
                        CreateUserId = 1,
                        Pid = 0,
                        UpdateUserId = 1,
                        SortCode = 0,
                        QCount = 1
                    });
                    db.SaveChanges();
                    foreach (var item2 in item.CategoryList)
                    {
                        var LevelOne = db.Category.First(m => m.Ali_id == item.id.ToString() && m.Pid == 0);

                        db.Category.Add(new Category()
                        {
                            Name = item2.name,
                            ShortName = item2.name,
                            Ali_id = item2.id.ToString(),
                            ShowWeb = false,
                            ShowPhone = false,
                            UpdateTime = DateTime.Now,
                            CreateTime = DateTime.Now,
                            CreateUserId = 1,
                            Pid = LevelOne.Id,
                            UpdateUserId = 1,
                            SortCode = 0,
                            QCount = 1
                        });
                    }
                    db.SaveChanges();
                }
                else
                {
                    var LevelOne = db.Category.First(m => m.Ali_id == item.id.ToString() && m.Pid == 0);
                    LevelOne.QCount += 1;
                    db.Entry<Category>(LevelOne).Property(m => m.QCount).IsModified = true;
                    foreach (var item3 in item.CategoryList)
                    {

                        if (!db.Category.Any(m => m.Ali_id == item3.id.ToString()))
                        {
                            db.Category.Add(new Category()
                            {
                                ShortName = item3.name,
                                Name = item3.name,
                                Ali_id = item3.id.ToString(),
                                ShowWeb = false,
                                ShowPhone = false,
                                UpdateTime = DateTime.Now,
                                CreateTime = DateTime.Now,
                                CreateUserId = 1,
                                Pid = LevelOne.Id,
                                UpdateUserId = 1,
                                SortCode = 0,
                                QCount = 1
                            });
                        }
                        else
                        {
                            var LevelTwo = db.Category.First(m => m.Ali_id == item3.id.ToString());
                            LevelTwo.QCount += 1;
                            db.Entry<Category>(LevelTwo).Property(m => m.QCount).IsModified = true;
                        }

                    }
                    db.SaveChanges();
                }
            }


            return View();
        }
    }
}